/*
 * @Author: wangwei wwdqq7@qq.com
 * @Date: 2025-04-01 15:00:00
 * @LastEditors: wangwei wwdqq7@qq.com
 * @LastEditTime: 2025-04-01 22:35:18
 * @FilePath: /FullStack/pro/typeorm-mysql/src/auth/auth.service.ts
 * @Description: 认证服务，提供用户验证和JWT令牌生成
 */
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';

import { User } from '@/entity/User';
import { UserService } from '@/user/user.service';

@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private jwtService: JwtService,
  ) {}

  /**
   * 验证用户
   * @param username 用户名
   * @param password 密码
   * @returns 验证通过返回用户信息，否则返回null
   */
  async validateUser(
    username: string,
    password: string,
  ): Promise<Omit<User, 'password'> | null> {
    const response = await this.userService.getUsers();
    if (response.code !== 0) return null;

    const user = response.data.find((user) => user.username === username);

    if (user && user.password === password) {
      // 实际应用中应使用加密比较
      const { password, ...result } = user;
      console.log(password, result);
      return result;
    }
    return null;
  }

  /**
   * 用户登录
   * @param user 用户信息
   * @returns JWT访问令牌
   */
  async login(user: { username: string; id: number }) {
    interface JwtPayload {
      username: string;
      sub: number;
    }
    const payload: JwtPayload = { username: user.username, sub: user.id };
    return {
      access_token: await this.jwtService.sign(payload),
    };
  }
}
